package com.gs.wechatdemo.util;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.util.Base64;
import android.util.DisplayMetrics;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.CustomTarget;
import com.bumptech.glide.request.transition.Transition;
import com.gs.wechatdemo.MyApplication;
import com.gs.wechatdemo.control.GlideRoundTransform;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;

public class ImageUtil {

    private static final String photoPath = FileUtils.getInstance().getExternalFilePath(MyApplication.getContext()) + "/photo_";

    public static void loadImg(Activity activity, String url, ImageView iv) {
        if (ActivityUtil.isSurvive(activity)) {
            Glide.with(activity)
                    .load(url)
                    .skipMemoryCache(false)
                    .into(iv);
        }
    }

    public static void loadRadiusImg(Context context, String url, ImageView iv, float radius) {
        Glide.with(context)
                .load(url)
                .apply(getOptions(radius))
                .centerCrop()
                .skipMemoryCache(false)
                .into(iv);
    }

    public static void loadRadiusImg(Context context, Bitmap url, ImageView iv, float radius) {
        Glide.with(context)
                .load(url)
                .apply(getOptions(radius))
                .skipMemoryCache(false)
                .into(iv);
    }

    public static void loadBitmap(Activity activity, Bitmap bitmap, ImageView iv) {
        if (ActivityUtil.isSurvive(activity)) {
            Glide.with(activity)
                    .load(bitmap)
                    .fitCenter()
                    .skipMemoryCache(false)
                    .into(iv);
        }
    }

    /**
     * 刷新圖片，不使用緩存
     *
     * @param activity
     * @param url
     * @param iv
     */
    public static void loadImgWithout(Activity activity, String url, ImageView iv) {
        if (ActivityUtil.isSurvive(activity)) {
            Glide.with(activity)
                    .load(url)
                    .skipMemoryCache(true)
                    .diskCacheStrategy(DiskCacheStrategy.NONE)
                    .into(iv);
        }
    }

    public static String getLocalPhoto(String userId) {
        return photoPath + userId + ".jpg";
    }

    public static void getBitmap(Context context, String imgUrl, final Handler handler, final int arg) {
        Glide.with(context)
                .asBitmap()
                .load(imgUrl)
                .skipMemoryCache(false)
                .into(new CustomTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                        Message message = Message.obtain();
                        message.what = 1;
                        message.arg1 = arg;
                        message.obj = resource;
                        handler.sendMessage(message);
                    }

                    @Override
                    public void onLoadCleared(@Nullable Drawable placeholder) {

                    }
                });
    }

    public static String saveBitmap(Context context, Bitmap bitmap) {
        FileOutputStream fops = null;
        String path = "";
        File saveFile = FileUtils.getInstance().createFile(context, "demo_image_" + DateUtil.DateTimeToStr(new Date(), "yyyyMMdd_hhmmss") + ".jpg");
        path = saveFile.getAbsolutePath();
        try {
            fops = new FileOutputStream(path);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fops);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fops != null) {
                    fops.flush();
                    fops.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return path;
    }

    public static Bitmap resizeBitmap(Bitmap bitmap, int newWidth) {
        Bitmap resizeBmp = null;
        if (bitmap != null) {
            int width = bitmap.getWidth();
            int height = bitmap.getHeight();
            float scale = ((float) width) / height;
            Matrix matrix = new Matrix();
            matrix.postScale(scale, scale);
            resizeBmp = Bitmap.createBitmap(bitmap, 0, 0, newWidth, (int) (height * scale), matrix, true);
        }
        return resizeBmp;
    }

    public static Bitmap resizeBitmapWithWindow(Bitmap bitmap) {
        DisplayMetrics dm = MyApplication.getContext().getResources().getDisplayMetrics();
        int newWidth = dm.widthPixels;
        return resizeBitmap(bitmap, newWidth);
    }

    private static RequestOptions getOptions(float radius) {
        return new RequestOptions()
                .transform(new GlideRoundTransform(radius));
    }

    public static String bitmapToBase64(Bitmap bitmap) {
        String result = null;
        ByteArrayOutputStream baos = null;
        try {
            if (bitmap != null) {
                baos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
                baos.flush();
                baos.close();
                byte[] bitmapBytes = baos.toByteArray();
                result = Base64.encodeToString(bitmapBytes, Base64.DEFAULT);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (baos != null) {
                    baos.flush();
                    baos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    public static Bitmap base64ToBitmap(String base64String) {
        base64String = Uri.decode(base64String);
        byte[] decode = Base64.decode(base64String, Base64.DEFAULT);
        Bitmap bitmap = BitmapFactory.decodeByteArray(decode, 0, decode.length);
        return bitmap;
    }

    public static Bitmap bitmapToGray(Bitmap bmpSrc) {
        int width, height;
        width = bmpSrc.getWidth();
        height = bmpSrc.getHeight();
        Bitmap bmpGray = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
        Canvas c = new Canvas(bmpGray);
        Paint paint = new Paint();
        ColorMatrix cm = new ColorMatrix();
        cm.setSaturation(0);
        ColorMatrixColorFilter f = new ColorMatrixColorFilter(cm);
        paint.setColorFilter(f);
        c.drawBitmap(bmpSrc, 0, 0, paint);
        return bmpGray;
    }
}
